package cn.neusoft.controller;

import cn.neusoft.domain.CargoBuyBill;
import cn.neusoft.domain.CargoDescription;
import cn.neusoft.service.BuyBillService;
import cn.neusoft.service.CargoAndDescriptionService;
import cn.neusoft.tool.PageSet;
import cn.neusoft.vo.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("/buyBill")
public class BuyBillController {
    @Autowired
    private BuyBillService buyBillService;
    @Autowired
    private CargoAndDescriptionService cargoAndDescriptionService;
    private static final String UNSETTED_UNIT = "未设置";
    private static final String UNSETTED_ID = "不存在";

    @GetMapping("/deleteBuyBill/{id}")
    public synchronized ResultBean deleteBuyBill(@PathVariable int id){
        ResultBean resultBean = null;

        switch(buyBillService.deleteBuyBill(id)){
            case 1:
                resultBean = ResultBean.success();
                break;
            default:
                resultBean = ResultBean.error(7078, "错误");
        }



        resultBean = ResultBean.success();
        return resultBean;
    }
    @PostMapping("/getAllBuyPage")
    public ResultBean getAllBuyPage(@RequestBody Map<String, String> map){
        ResultBean resultBean = null;
        List<CargoBuyBillReturn> ans = new ArrayList<CargoBuyBillReturn>();


        try{
            int pageNum = Integer.parseInt(map.get("pageNum"));
            int pageSize = Integer.parseInt(map.get("pageSize"));
            Date from =  null;
            Date to = null;
            if(!map.get("from").equals("")){
                from = new SimpleDateFormat("yyyy-MM-dd").parse(map.get("from"));
            }
            if(!map.get("to").equals("")){
                to = new SimpleDateFormat("yyyy-MM-dd").parse(map.get("to"));
            }
            String type = map.get("stage");

            List<CargoBuyBill> list = buyBillService.queryAllBuyBill();

            for(CargoBuyBill c : list){
                if(from != null && (c.getDate().compareTo(from) < 0) ){
                    System.out.println(from.toString());
                    continue;
                }
                if(to != null && (c.getDate().compareTo(to) > 0)){
                    continue;
                }
                System.out.println("1");
                System.out.println(c.getStage() + "222" + type);
                if(c.getStage().equals(type)){
                    System.out.println("2");

                    List<TableElement> line = new ArrayList<>();
                    for(Map.Entry<String, Double> entry : c.getCargosInf().entrySet()){
                        CargoDescription cargo = cargoAndDescriptionService.getByDesName(entry.getKey());
                        TableElement tableElement = null;
                        if(cargo != null){
                            tableElement = new TableElement(cargo.getName(), cargo.getUnit(), Double.toString(entry.getValue()), "" + cargo.getId());
                        }
                        else{
                            tableElement = new TableElement(entry.getKey(), UNSETTED_UNIT, Double.toString(entry.getValue()), UNSETTED_ID);
                        }
                        System.out.println(tableElement);
                        line.add(tableElement);
                    }
                    CargoBuyBillReturn cargoBuyBillReturn = new CargoBuyBillReturn(c.getId(), c.getDate(), line, c.getStage(), c.getWarehouseName());
                    System.out.println(cargoBuyBillReturn);
                    ans.add(cargoBuyBillReturn);

                }
            }


            PageSet<CargoBuyBillReturn> pageSet = new PageSet<CargoBuyBillReturn>(ans, pageSize);
            Map<String, Object> answer = new HashMap<>();
            answer.put("total", pageSet.getTotal());
            answer.put("list", pageSet.getPage(pageNum));

            resultBean = ResultBean.success(answer);

        }catch(Exception e){
            e.printStackTrace();
            resultBean = ResultBean.error(1, "错误");
        }
        return resultBean;
    }

    @PostMapping("/queryAllBuyBill")
    public ResultBean queryAllBuyBill(){
        ResultBean resultBean = null;

        resultBean = ResultBean.success(buyBillService.queryAllBuyBill());

        return resultBean;
    }

    @PostMapping("/changeBuyBill")
    public ResultBean changeBuyBill(@RequestBody Map<String, Object> map){
      ResultBean resultBean;

      if(map != null){
        try{
          int id = (int) map.get("id");
          CargoBuyBill find = buyBillService.getBuyBillByID(id);
          if(find != null){
              java.sql.Date date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("date")).getTime());
              String stage;
              if(map.get("stage") != null){
                  stage = (String) map.get("stage");
              }
              else{
                  stage = "入库";
              }
              String warehouseName = (String) map.get("warehouseName");
              List<Map<String, Object>> carLines = (List<Map<String, Object>>) map.get("planCargoInf");
              Map<String, Double> temp = new HashMap<>();
              System.out.println("!");

              for(Map<String, Object> m : carLines){
                  System.out.println(m.toString());
                  System.out.println(m.get("quantities"));
                  temp.put((String) m.get("cargoName"), Double.valueOf((String) m.get("quantities")));
              }

              find.setDate(date);
              find.setWarehouseName(warehouseName);
              find.setStage(stage);
              find.setCargosInf(temp);

              int reply = buyBillService.changeBuyBill(find);
              switch(reply){
                  case 1:
                      resultBean = ResultBean.success();
                      break;
                  case 0:
                      resultBean = ResultBean.error(7011, "失败");
                      break;
                  default:
                      resultBean = ResultBean.error(7012, "未知错误");
                      break;
              }
          }
          else{
              resultBean = ResultBean.error(7012, "未知错误");

          }

        }
        catch (Exception e){
          e.printStackTrace();
          resultBean = ResultBean.error(7013, "错误");
        }
      }
      else{
        resultBean = ResultBean.error(7010, "输入为空");
      }

      return resultBean;
    }

    @PostMapping("/generateBuyBill")
    public synchronized ResultBean generateBuyBill(@RequestBody Map<String, Object> map){
        ResultBean resultBean;

        if(map != null){
            try{
                java.sql.Date date = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse((String) map.get("date")).getTime());
                String warehouseName = (String) map.get("warehouseName");
                List<Map<String, String>> carLines = (List<Map<String, String>>) map.get("planCargoInf");
                Map<String, Double> temp = new HashMap<>();
                for(Map<String, String> m : carLines){
                    temp.put(m.get("cargoName"), Double.valueOf(m.get("quantities")));
                }


                CargoBuyBill cargoBuyBill = new CargoBuyBill(date, temp, "入库", warehouseName);

                int reply = buyBillService.generateBuyBill(cargoBuyBill);
                switch(reply){
                    case 1:
                        resultBean = ResultBean.success();
                        break;
                    case 0:
                        resultBean = ResultBean.error(7011, "失败");
                        break;
                    default:
                        resultBean = ResultBean.error(7012, "未知错误");
                        break;
                }
            }
            catch (Exception e){
                e.printStackTrace();
                resultBean = ResultBean.error(7013, "错误");
            }
        }
        else{
            resultBean = ResultBean.error(7010, "输入为空");
        }

        return resultBean;
    }

    private class CargoBuyBillReturn{
        private int id;
        private java.sql.Date date;
        private List<TableElement> list;
        private String stage;
        private String warehouseName;

        @Override
        public String toString() {
            return "CargoBuyBillReturn{" +
                    "id=" + id +
                    ", date=" + date +
                    ", list=" + list +
                    ", stage='" + stage + '\'' +
                    ", warehouseName='" + warehouseName + '\'' +
                    '}';
        }

        public CargoBuyBillReturn(int id, java.sql.Date date, List<TableElement> list, String stage, String warehouseName) {
            this.id = id;
            this.date = date;
            this.list = list;
            this.stage = stage;
            this.warehouseName = warehouseName;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public java.sql.Date getDate() {
            return date;
        }

        public void setDate(java.sql.Date date) {
            this.date = date;
        }

        public List<TableElement> getList() {
            return list;
        }

        public void setList(List<TableElement> list) {
            this.list = list;
        }

        public String getStage() {
            return stage;
        }

        public void setStage(String stage) {
            this.stage = stage;
        }

        public String getWarehouseName() {
            return warehouseName;
        }

        public void setWarehouseName(String warehouseName) {
            this.warehouseName = warehouseName;
        }
    }

    private class TableElement{
        private String cargoName;
        private String unit;
        private String quantities;

        private String id;

        @Override
        public String toString() {
            return "TableElement{" +
                    "cargoName='" + cargoName + '\'' +
                    ", unit='" + unit + '\'' +
                    ", quantities=" + quantities +
                    ", id=" + id +
                    '}';
        }

        public TableElement(String cargoName, String unit, String quantities, String id) {
            this.cargoName = cargoName;
            this.unit = unit;
            this.quantities = quantities;
            this.id = id;
        }

        public String getCargoName() {
            return cargoName;
        }

        public void setCargoName(String cargoName) {
            this.cargoName = cargoName;
        }

        public String getUnit() {
            return unit;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }

        public String getQuantities() {
            return quantities;
        }

        public void setQuantities(String quantities) {
            this.quantities = quantities;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }
    }
}
